package com.ds.utils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

import lombok.extern.slf4j.Slf4j;

import org.springframework.http.HttpHeaders;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

@Slf4j
public class WxUtils {
	
	static String token =null;
	static String ticket =null;
	
	static long token_time ;
	
	static long ticket_time ;
	//1.8小时
	static long hours_ms = 6480000;
	
	final static String tokenUrl ="https://api.weixin.qq.com/cgi-bin/token?grant_type="
			+ "client_credential&appid=wx69e334757b536987&secret=32be84a84fdb09d76072769b9ca58f54";
	public static void main(String[] args) {
		System.out.println(getSignature("http://www.wenma.com.cn/WMWXWebSite/profile.html"));
	}
	
	public static JSONObject getSignature(String url){
		String appid =  "wx69e334757b536987";
        String secret = "32be84a84fdb09d76072769b9ca58f54";

        String accessToken = getToken();
        String jsapiTicket = getTicket(accessToken);
//        String accessToken = "37_JSGB4H68dUfl1-6tNUndhXG7iO8GO8ldRJp0ExGemeo4DxuOurXqmmPb532fTMeChIAO5QlthQ2ces0Vx6fDFcnw27XRRPIREdwWYjNQD1QAppV9YYHEvoPvs9x6VCxdICJrzEcTv82MsIN1ZCYfAFAFIE";
//        String jsapiTicket = "kgt8ON7yVITDhtdwci0qeUeAR3vvlDOlU-3YbIKcbqsocCLqPWS1UsD2D8IYNvYNIo0hR-v93wVv-JKenMVzBA";
        String noncestr = UUID.randomUUID().toString().replace("-", "").substring(0, 16);
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String str = "jsapi_ticket="+jsapiTicket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url=" + url;
        log.info("签名前。。。{}",str);
        //6、将字符串进行sha1加密
        String signature =SHA1(str);
        log.info("signature。。。{}",signature);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("access_token", accessToken);
        jsonObject.put("appid", appid);
        jsonObject.put("secret", secret);
        jsonObject.put("jsapi_ticket", jsapiTicket);
        jsonObject.put("noncestr", noncestr);
        jsonObject.put("timestamp", timestamp);
        jsonObject.put("signature", signature);
		return jsonObject;
		
	}  
	
	public static String getToken(){
		if(token!=null){
			long now = System.currentTimeMillis();
			if((now-token_time)<hours_ms){
				log.info("获取token,未过期。result={}",token);
				return token;
			}
		}
		String result = HttpClient.sendGetRequest(tokenUrl, null,new  HttpHeaders());
		JSONObject jsonObject = JSON.parseObject(result);
		token = jsonObject.getString("access_token");
		log.info("获取token,result={}",result);
		token_time = System.currentTimeMillis();
		return token;
	}
	
    public static String getTicket(String access_token) {
    	
    	if(ticket!=null){
			long now = System.currentTimeMillis();
			if((now-ticket_time)<hours_ms){
				log.info("获取ticket,未过期。result={}",ticket);
				return ticket;
			}
		}
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";
        String result = HttpClient.sendGetRequest(url, null,new  HttpHeaders());
        JSONObject jsonObject = JSON.parseObject(result);
        ticket = jsonObject.getString("ticket");
        ticket_time = System.currentTimeMillis();
        log.info("获取ticket,result={}",result);
        return ticket;
    }
    
    public static String SHA1(String decript) {
        try {
            MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1");
            digest.update(decript.getBytes());
            byte messageDigest[] = digest.digest();
            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            // 字节数组转换为 十六进制 数
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

}
